package com.sptpc.demo.service.impl;

import com.sptpc.demo.controller.requests.SearchOrderRequest;
import com.sptpc.demo.model.Drink;
import com.sptpc.demo.model.Order;
import com.sptpc.demo.repository.DrinkRepository;
import com.sptpc.demo.repository.OrderRepository;
import com.sptpc.demo.service.IOrderService;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

@Service
public class OrderJpaService implements IOrderService {
    @Autowired
    public OrderRepository orderRepository;

    @Autowired
    private DrinkRepository drinkRepository;


    @Override
    public Order addNewOrder(Order newOrder) {
        BigDecimal totalPrice = newOrder.getItems().stream()
                .map(drink -> drink.getPrice().getAmount())
                .reduce(BigDecimal.ZERO,((total,price) -> total.add(price)));
        newOrder.setPrice(Money.of(CurrencyUnit.of("CNY"),totalPrice));
        return orderRepository.saveAndFlush(newOrder);
    }

    @Override
    public Page<Order> searchOrders(SearchOrderRequest condition, PageRequest page) {
        LocalDate start = condition.getStartDate();
        LocalDate end = condition.getEndDate();
        Integer state = condition.getState();
        Page<Order> orders = orderRepository.findOrdersByCreateTimeBetweenOrState(start
        ,end,state,page);
        return orders;
    }

    @Override
    public void addNewOrder000(Order order, List<Integer> items) {
        order.setState(0);
        List<Drink> drinks = drinkRepository.findAllById(items);
        order.setItems(drinks);
        BigDecimal price = BigDecimal.ZERO;
        for (Drink drink : drinks) {
            price = price.add(drink.getPrice().getAmount());
        }

        drinks.stream().map(drink -> drink.getPrice().getAmount());

        order.setPrice(Money.of(CurrencyUnit.of("CNY"),price));
        orderRepository.save(order);
    }

    @Override
    public void deleteOrder(Integer id) {
        orderRepository.deleteById(id);
    }

    @Override
    public Order getOrderById(Integer id) {
        return orderRepository.findById(id).orElse(null);
    }

    @Override
    public void updateOrder(Order order) {
        orderRepository.save(order);
    }

    @Override
    public List<Order> findOrdersByCustomer(String customer) {
        Order order = new Order();
        order.setCustomer(customer);
//        order.setState(0);
//        动态生成where条件，判断属性里面是否有值，有值才会生成
        Example<Order> example = Example.of(order);
        return orderRepository.findAll(example);
    }
}
